
import config from 'config';
import { defineStore } from 'pinia';
import { useAuthUserStore } from './authuserStore';
import { ElNotification } from 'element-plus';
import { useMainStore } from './mainStore';


interface IState {
  websocket: WebSocket | null;
  websocketStatus: boolean;
  recvList: any[];
}

type IResult = {
  packetLen: number,
  headerLen: number,
  ver: number,
  op: number,
  seq: number,
  body: any
}

/**
 * blob blob数据
 * call 回调 解析数据会通过回调返回数据
 */

// 文本解码器
const textDecoder: TextDecoder = new TextDecoder('utf-8');

// 从buffer中读取
const readInt = (buffer: Uint8Array, start: number, len: number) => {
  let result = 0
  for (let i = len - 1; i >= 0; i--) {
    result += Math.pow(256, len - i - 1) * buffer[start + i]
  }
  return result
}

const decode = (blob: Blob, call: any) => {
  let reader: FileReader = new FileReader();
  reader.onload = <T extends ProgressEvent<FileReader>>(e: T) => {
    let buffer: Uint8Array = new Uint8Array(e.target?.result as ArrayBuffer);
    let result: IResult = {
      packetLen: readInt(buffer, 0, 4),
      headerLen: readInt(buffer, 4, 2),
      ver: readInt(buffer, 6, 2),
      op: readInt(buffer, 8, 4),
      seq: readInt(buffer, 12, 4),
      body: []
    }
    let offset = 0;
    while (offset < buffer.length) {
      let packetLen = readInt(buffer, offset, 4)
      let headerLen = 16
      let data = buffer.slice(offset + headerLen, offset + packetLen);
      let body = "{}"
      body = textDecoder.decode(data);
      if (body) {
        // 同一条消息中可能存在多条信息，用正则筛出来
        // 去除干扰字符
        const group = body.split(/[\x00-\x1f]+/);
        group.forEach(item => {
          try {
            result.body.push(JSON.parse(JSON.parse(item)));
          } catch (e) {
            // 忽略非JSON字符串，通常情况下为分隔符
          }
        });
      }
      offset += packetLen;
    }
    //回调
    call(result);
  }
  // 读取blob数据
  reader.readAsArrayBuffer(blob);
}


export const useWebsocketStore = defineStore('websocketStore', {
  state: (): IState => ({
    websocket: null,
    websocketStatus: false,
    recvList: [],
  }),
  getters: {
    getRecvList(): any[] { return this.recvList; }
  },
  actions: {
    close() {
      if (this.websocket) {
        this.websocket.close();
      }
    },
    connectWebsocket() {
      const userStore = useAuthUserStore();
      if (userStore.isAuth) {
        // this.websocket = new WebSocket(`${import.meta.env.VITE_APP_WEBSOCKET_URL}/ws/user-${userStore.id}/?AccessToken=${userStore.access}`);


        if (this.websocket) {
          this.websocket.onopen = () => {
            console.log(`user-${userStore.id} ws连接成功`);
            this.websocketStatus = true;
          };
          this.websocket.onclose = () => {
            console.log(`user-${userStore.id} ws连接关闭`);
            this.websocketStatus = false;
            this.websocket = null;
          };
          this.websocket.onmessage = (evt: MessageEvent) => {
            decode(evt.data, (packet: IResult) => {
              //解码成功回调 op = 1 代表接收到的是消息通知
              if (packet.op === 1) {
                const element = packet.body;
                //解包之后的数据
                this.recvWebsocket(element[0]);
              }
            });
          }
        };
      }

    },
    recvWebsocket(data: any) {
      this.recvList = data;
      const mainStore = useMainStore();

      mainStore.flushUnread();

      ElNotification({
        title: '消息通知',
        message: data.title,
        type: 'success',
        duration: 0
      });
    }
  },
});
